﻿using GPS.MODELS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GPS.DataAccessLayer;
using AutoMapper;
using PagedList;
using GPS.ENTITYS;
using GPS.COMMON;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Oracle.ManagedDataAccess.Client;
using System.Data;
using Microsoft.AspNet.Identity;
using NPOI.HSSF.UserModel;
using OfficeOpenXml;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace GPS.Controllers.GPS_BaoCao
{
    public class GPS_CB_PT_DUP_BIENSOController : Controller
    {
        #region Oninit
        DbContextHelper<GPS_NVContext> _db = Singleton<DbContextHelper<GPS_NVContext>>.Inst;
        public GPS.MODELS.ApplicationUser getCurrentUser()
        {
            ApplicationDbContext dbUser = new ApplicationDbContext();
            string userId = User.Identity.GetUserId();
            ApplicationUser _currentUser = dbUser.Users.Find(userId);
            return _currentUser;
        }
        public void initialCategorySearchAction(ViewReportModelGPS_CB_PT_DUP_BIENSO SearchModel)
        {
            ViewBag.checkuser = this.getCurrentUser().MA_TINHTP;
           // string getdvgtvt_Ma = GPS.DAL.Check_User.CheckUser(this.getCurrentUser().MA_TINHTP, SearchModel.pDVGTVT_MA);
            //SearchModel.pDVGTVT_MA = getdvgtvt_Ma;
        }
        #endregion

        #region Index
        public ActionResult Index(ViewReportModelGPS_CB_PT_DUP_BIENSO SearchModel, int? currentPage)
        {
            initialCategorySearchAction(SearchModel);
            
            var model = new List<RepostModelGPS_CB_PT_DUP_BIENSO>();

            if (!string.IsNullOrEmpty(SearchModel.pPT_BIENSO) && SearchModel.ExportButton == "Search")
            {
                Int16 icount = 1;
                model = Getdata(SearchModel);
                foreach (var currentEntity in model)
                {
                    currentEntity.STT = icount;
                    icount++;
                }
                ViewBag.TotalRow = model.Count();
            }
            

            if (SearchModel.ExportButton == "Xuất Excel")
            {
                try
                {
                    Int16 icount = 1;
                    model = Getdata(SearchModel);
                    foreach (var currentEntity in model)
                    {
                        currentEntity.STT = icount;
                        icount++;
                    }
                    ViewBag.TotalRow = model.Count();
                    FileInfo template = new FileInfo(Server.MapPath(@"\Templates\GPS_Excel\CB_PhuongTienTrungBienSo.xlsx"));
                    FileInfo newFile = new FileInfo(Server.MapPath(@"\Templates\GPS_Excel\CB_DonViHetHanGiayPhepNEW.xlsx"));

                    // Using the template to create the newFile...
                    using (OfficeOpenXml.ExcelPackage excelPackage = new OfficeOpenXml.ExcelPackage(newFile, template))
                    {
                        // Getting the complete workbook...
                        ExcelWorkbook myWorkbook = excelPackage.Workbook;
                        // Getting the worksheet by its name...
                        ExcelWorksheet myWorksheet = myWorkbook.Worksheets["Sheet1"];
                        string tendvgtvt = "";
                        int recordIndex = 4;
                        foreach (var item in model)
                        {
                            myWorksheet.Cells[recordIndex, 1].Value = item.STT.ToString();
                            myWorksheet.Cells[recordIndex, 2].Value = item.PT_BIENSO == null ? "" : item.PT_BIENSO;
                            myWorksheet.Cells[recordIndex, 3].Value = item.DVGTVT_TEN == null ? "" : item.DVGTVT_TEN;
                            myWorksheet.Cells[recordIndex, 4].Value = item.PT_GPXTL == null ? "" : item.PT_GPXTL.ToString();
                            myWorksheet.Cells[recordIndex, 5].Value = item.PT_SOGPXTL == null ? "" : item.PT_SOGPXTL;
                            myWorksheet.Cells[recordIndex, 6].Value = item.PT_CQCAPGPXTL == null ? "" : item.PT_CQCAPGPXTL;
                            tendvgtvt = item.DVGTVT_TEN;
                            recordIndex++;
                        }
                        //string tendvgtvt = _db.GetOne<SDONVIGTVT>(x => x.DVGTVT_MA == SearchModel.pDVGTVT_MA).DVGTVT_TEN;
                        myWorksheet.Cells[2, 1].Value = "Đơn vị kinh doanh vận tải: " + tendvgtvt;
                        excelPackage.Save();
                    }
                    string contentType = string.Empty;
                    string CurrentFileName = Server.MapPath(@"\Templates\GPS_Excel\CB_DonViHetHanGiayPhepNEW.xlsx");
                    if (CurrentFileName.Contains(".xlsx"))
                    {
                        contentType = "application/msexcel";
                    }
                    return File(CurrentFileName, contentType, string.Format("CanhBaoPhuongTienTrungBienSo_{0}.xlsx", DateTime.Now.ToShortDateString().Replace("/","_")));
                }
                catch (Exception ex)
                {
                    TempData["Message"] = ex.ToString();
                    return RedirectToAction("Index");
                }
            }
            else
            {
                Int16 icount = 1;
                model = Getdata(SearchModel);
                foreach (var currentEntity in model)
                {
                    currentEntity.STT = icount;
                    icount++;
                }
                ViewBag.TotalRow = model.Count();
                var pageIndex = SearchModel.Page ?? 1;
                SearchModel.SearchResults = model.ToPagedList(pageIndex, GPS.COMMON.Constants.PageSize);
                return View(SearchModel);
            }
        }
        #endregion

        public List<RepostModelGPS_CB_PT_DUP_BIENSO> Getdata(ViewReportModelGPS_CB_PT_DUP_BIENSO SearchModel)
        {
            var _pPT_BIENSO = new OracleParameter("pPT_BIENSO", OracleDbType.Varchar2, (SearchModel.pPT_BIENSO == null ? DBNull.Value : (object)SearchModel.pPT_BIENSO), ParameterDirection.Input);
            var _pRET = new OracleParameter("pRET", OracleDbType.RefCursor, ParameterDirection.Output);
            var entities = _db.DbContext.Database.SqlQuery<RepostModelGPS_CB_PT_DUP_BIENSO>("BEGIN GPS_CANHBAO.GPS_CANHBAO_PT_DUP_BIENSO(:pPT_BIENSO,:pRET); end;", _pPT_BIENSO, _pRET).ToList();
            return entities;
        }
    }
}